/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.Random;

/**
 *
 * @author Andrea
 */
public class Utility {
    private static final Utility INSTANCE;
    static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?!:.;,ì^'+*!\"£$%&/()=";
    
    static {
        INSTANCE = new Utility();
    }
    
    private Utility() {
    }
    
    

   public static byte[] longToBytes(long x) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / 8);
        buffer.putLong(x);
        return buffer.array();
    }

    public static long bytesToLong(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / 8);
        buffer.put(bytes);
        buffer.flip();//need flip 
        return buffer.getLong();
    }
    
    public static byte[] intToBytes(int x) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / 8);
        buffer.putLong(x);
        return buffer.array();
    }

    public static int bytesToint(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / 8);
        buffer.put(bytes);
        buffer.flip();//need flip 
        return buffer.getInt();
    }
    
    public static byte[] shortToBytes(short x) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / 8);
        buffer.putLong(x);
        return buffer.array();
    }

    public static short bytesToshort(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / 8);
        buffer.put(bytes);
        buffer.flip();//need flip 
        return buffer.getShort();
    }
    
    public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b);
        o.writeObject(obj);
        return b.toByteArray();
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream b = new ByteArrayInputStream(bytes);
        ObjectInputStream o = new ObjectInputStream(b);
        return o.readObject();
    }
    
    public static String generatePassword(){
        Random rnd = new Random();
        int length  = rnd.nextInt(32);
        
        StringBuilder sb = new StringBuilder(length);
        
        for (int i = 0; i < length; i++) {
            sb.append(ALPHABET.charAt(rnd.nextInt(ALPHABET.length())));
        }
        
        return sb.toString();
    }
}
